package com.cmas.platform.utils;

import com.alibaba.fastjson2.JSONObject;
import com.cmas.platform.config.NettyConfig;
import com.cmas.platform.domain.Message;
import com.cmas.platform.domain.Notification;
import com.cmas.platform.domain.em.MessageTypeEnum;
import com.cmas.platform.dto.PushMessageDto;
import com.cmas.platform.vo.LastNotificationVo;
import com.cmas.platform.vo.NotificationVo;
import io.netty.channel.Channel;
import io.netty.channel.group.ChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * @Author su
 * @Date 2024/5/16 17:50
 */
@Component
public class PushNoticeUtils {

    /**
     * 发送个体聊天消息
     *
     * @param message
     */
    public static void sendChatMsg(Message message) {
        pushUserMessage(message.getToId(), setData(MessageTypeEnum.CHAT_TEXT.getValue(),
                JSONObject.toJSONString(message)));
    }

    /**
     * 推送个人系统信息
     * @param notification
     */
    public static void pushUserNotification(Notification notification) {
        pushUserMessage(notification.getUserId(), setData(MessageTypeEnum.NOTIFICATION.getValue(),
                JSONObject.toJSONString(notification)));
    }


    /**
     * 推送地区通知
     *
     * @param lastNotificationVo
     */
    public static void pushRegionNotification(LastNotificationVo lastNotificationVo) {
        ChannelGroup channelGroup = NettyConfig.getOnlineUserGroupChannelMap().get(lastNotificationVo.getRegionId());
        if (Objects.nonNull(channelGroup)) {
            channelGroup.writeAndFlush(setData(MessageTypeEnum.NOTIFICATION.getValue(),
                    JSONObject.toJSONString(lastNotificationVo)));
        }
    }


    private static void pushUserMessage(String userId, TextWebSocketFrame textWebSocketFrame) {
        Channel channel = NettyConfig.getOnlineUserChannelMap().get(userId);
        if (Objects.nonNull(channel)) {
            //将消息发送给指定的用户
            channel.writeAndFlush(textWebSocketFrame);
        }
    }

    private static TextWebSocketFrame setData(String type, String data) {
        return new TextWebSocketFrame(JSONObject.toJSONString(new PushMessageDto(data, type)));
    }

}
